package gdufs.lkl.calculator;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.List;

public class CustomFunctionAdapter extends RecyclerView.Adapter<CustomFunctionAdapter.FunctionViewHolder> {

    private final List<CustomFunction> functions;
    private final OnFunctionClickListener listener;

    public interface OnFunctionClickListener {
        void onFunctionClick(CustomFunction function);
    }

    public CustomFunctionAdapter(List<CustomFunction> functions, OnFunctionClickListener listener) {
        this.functions = functions;
        this.listener = listener;
    }

    @NonNull
    @Override
    public FunctionViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_custom_function, parent, false);
        return new FunctionViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull FunctionViewHolder holder, int position) {
        CustomFunction function = functions.get(position);
        holder.bind(function, listener);
    }

    @Override
    public int getItemCount() {
        return functions.size();
    }

    static class FunctionViewHolder extends RecyclerView.ViewHolder {
        private final TextView nameTextView;
        private final TextView paramsTextView;
        private final TextView expressionTextView;

        public FunctionViewHolder(@NonNull View itemView) {
            super(itemView);
            nameTextView = itemView.findViewById(R.id.textViewFunctionName);
            paramsTextView = itemView.findViewById(R.id.textViewFunctionParams);
            expressionTextView = itemView.findViewById(R.id.textViewFunctionExpression);
        }

        public void bind(final CustomFunction function, final OnFunctionClickListener listener) {
            nameTextView.setText(function.getName());
            paramsTextView.setText("参数: " + function.getParametersAsString());
            expressionTextView.setText("表达式: " + function.getExpression());
            itemView.setOnClickListener(v -> listener.onFunctionClick(function));
        }
    }
}
